<?php
// +----------------------------------------------------------------------
// | SwiftPHP [ JUST DO ONE THING WELL ]
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2017  http://swiftphp.zhongwenyu.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhongwenyu <zhongwenyu1987@163.com> <http://www.zhongwenyu.com>
// +----------------------------------------------------------------------
// | Times: 2017/2/23 10:27
// +----------------------------------------------------------------------
namespace swift;

class Verify{
    protected $config =	array(
        'seKey'     =>  'swiftphp.zhongwenyu.com',   // 验证码加密密钥
        'codeSet'   =>  '2345678abcdefhijkmnpqrstuvwxyzABCDEFGHJKLMNPQRTUVWXY',             // 验证码字符集合
        'expire'    =>  1800,            // 验证码过期时间（s）
        'fontSize'  =>  25,              // 验证码字体大小(px)
        'useNoise'  =>  true,            // 是否添加杂点
        'imageH'    =>  0,               // 验证码图片高度
        'imageW'    =>  0,               // 验证码图片宽度
        'length'    =>  4,               // 验证码位数
        'fontttf'   =>  '',              // 验证码字体，默认5.ttf
        'bg'        =>  array(209, 209, 209),  // 背景颜色
        'reset'     =>  true,           // 验证成功后是否重置
    );

    protected $image = null;   // 验证码图像
    protected $color = null;   // 验证码颜色
    protected $error;

    /**
     * 架构方法 设置参数
     * @access public
     * @param  array $config 配置参数
     */
    public function __construct(array $config = []){
        $this->config = array_merge($this->config , $config);
    }

    public function getError(){
        return $this->error;
    }

    /**
     * 使用 $this->name 获取配置
     * @access public
     * @param  string $name 配置名称
     * @return multitype    配置值
     */
    public function __get($name){
        return $this->config[$name];
    }

    public function code(){
        $key = $this->authcode($this->seKey);
        return Session::get($key);
    }

    /**
     * 设置验证码配置
     * @access public
     * @param  string $name 配置名称
     * @param  string $value 配置值
     * @return void
     */
    public function __set($name , $value){
        if(isset($this->config[$name])){
            $this->config[$name] = $value;
        }
    }

    /**
     * 验证验证码是否正确
     * @access public
     * @param string $code 用户验证码
     * @param string $id 验证码标识
     * @return bool 用户验证码是否正确
     */
    public function check($code, $id = '') {
        $key = $this->authcode($this->seKey) . $id;
        $secode = Session::get($key);

        // 验证码不能为空
        if(empty($code) || empty($secode)){
            return false;
        }

        // 验证码过期
        if(TIME - $secode['verify_time'] > $this->expire){
            Session::delete($key);
            return false;
        }

        if($this->authcode(strtoupper($code)) == $secode['verify_code']){
            $this->reset && Session::delete($key);
            return true;
        }else{
            return false;
        }
    }

    /**
     * 输出验证码并把验证码的值保存的session中
     * 验证码保存到session的格式为： array('verify_code' => '验证码值', 'verify_time' => '验证码创建时间');
     * @access public
     * @param string $id 要生成验证码的标识
     * @return void
     */
    public function entry($id = '') {
        // 设置图片宽度
        $this->imageW || $this->imageW = $this->length*$this->fontSize*1.5 + $this->length*$this->fontSize/2;
        // 设置图片高度
        $this->imageH || $this->imageH = $this->fontSize * 2.5;
        // 新建画布
        $this->image = imagecreate($this->imageW , $this->imageH);
        // 添加背景色
        imagecolorallocate($this->image , $this->bg[0] , $this->bg[1] , $this->bg[2]);
        // 验证码字体颜色
        $this->color = imagecolorallocate($this->image , mt_rand(0 , 80) , mt_rand(0 , 80) , mt_rand(0 , 80));
        // 设置验证码字体
        if(empty($this->fontttf)){
            $this->fontttf = CORE_PATH . 'verify' . DS . 'fonts' . DS . '5.ttf';
        }
        if($this->useNoise){
            // 绘制杂点
            $this->writeNoise();
        }

        // 绘验证码
        $code = array(); // 验证码
        $codeNX = 0; // 验证码第N个字符的左边距
        for ($i = 0; $i<$this->length; $i++) {
            $code[$i] = $this->codeSet[mt_rand(0, strlen($this->codeSet)-1)];
            $codeNX  += mt_rand($this->fontSize*1.2, $this->fontSize*1.6);
            imagettftext($this->image, $this->fontSize, mt_rand(-40, 40), $codeNX, $this->fontSize*1.6, $this->color, $this->fontttf, $code[$i]);
        }

        // 保存验证码
        $key = $this->authcode($this->seKey);
        $auth = $this->authcode(strtoupper(implode('' , $code)));
        $secode = array();
        $secode['verify_code'] = $auth;
        $secode['verify_time'] = TIME;
        Session::set($key.$id , $secode);   // 将验证码信息保存到session中

        header('Cache-Control: private, max-age=0, no-store, no-cache, must-revalidate');
        header('Cache-Control: post-check=0, pre-check=0', false);
        header('Pragma: no-cache');
        header("content-type: image/png");
        // 输出图像
        imagepng($this->image);
        imagedestroy($this->image);
    }

    /**
     * 画杂点
     * 往图片上写不同颜色的字母或数字
     */
    private function writeNoise() {
        $codeSet = '2345678abcdefhijkmnpqrstuvwxyz';
        for($i = 0; $i < 10; $i++){
            //杂点颜色
            $noiseColor = imagecolorallocate($this->image, mt_rand(150,225), mt_rand(150,225), mt_rand(150,225));
            for($j = 0; $j < 5; $j++) {
                // 绘杂点
                imagestring($this->image, 5, mt_rand(-10, $this->imageW),  mt_rand(-10, $this->imageH), $codeSet[mt_rand(0, 29)], $noiseColor);
            }
        }
    }

    /**
     * 加密验证码
     */
    private function authcode($str){
        $key = substr(md5($this->seKey), 5, 8);
        $str = substr(md5($str), 8, 10);
        return md5($key . $str);
    }
}
